package com.lap.permission.component;

import com.lap.framework.tools.DateUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class SequenceHelper {
    public static final int TIME = 86400;

    private final StringRedisTemplate redisTemplate;

    public String getSeq(String prefix) {
        String key = (StringUtils.isNotBlank(prefix) ? prefix : "") + DateUtil.getString("yyyyMMdd");

        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        Long index = operations.increment(key, 1);
        if (index != null && index == 1) {
            operations.getAndExpire(key, TIME, TimeUnit.SECONDS);
        }

        return key + StringUtils.leftPad(String.valueOf(index), 6, "0");
    }

}
